package org.easyexcel.Test;

import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.LinkedList;

/**
 * @author DPF
 */
public class MyCP {
    public static void main(String[] args) {
        MessageQueue<Message> messageQueue = new MessageQueue<>(3);
        // 创建消息队列
        new Thread(() -> {
            for (int i = 1; i < 5; i++) {
                int id = i;
                Message message = new Message(id, "message" + i);
                System.out.println("生产者生产了消息：" + message);
                messageQueue.put(message);
            }
        }, "生产者").start();

        // 创建消费者
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                Message message = messageQueue.take();
                System.out.println("消费者消费了消息：" + message);
            }
        }, "消费者").start();
    }

    @Data
    @AllArgsConstructor
    static class MessageQueue<Message> {
        private final int capacity;
        private final LinkedList<Message> list = new LinkedList<>();
        Message take() {
            // 从消息队列中取出消息
            synchronized (list) {
                while (list.isEmpty()) {
                    System.out.println("队列为空，消费者线程等待...");
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Message message = list.removeFirst();
                list.notifyAll();
                return message;
            }
        }

        void put(Message message) {
            // 往消息队列中放入消息
            synchronized (list) {
                while (list.size() >= capacity) {
                    System.out.println("队列已满，生产者线程等待...");
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                list.addLast(message);
                list.notifyAll();
            }
        }
    }
    @Data
    @AllArgsConstructor
    final static class Message {
        private int id;
        private String message;
    }
}
